package org.toonWatch
import grails.converters.JSON

class VoucherController {
    
    def scaffold = true
    def springSecurityService

    static allowedMethods = [save: "POST", update: "POST", delete: "POST"]
    
    def index={
        redirect(action:"issueVoucher")
    }
    
  
    def issueVoucher = {    
    }
    
    def String wrapSearchParm(value) {
		 '%'+value+'%'
    }
    
    def mailService
    
    def search= {
        def list=User.findAllByNameIlike(wrapSearchParm(params.name))
        if (list) {println"found"}
 
        render(template:'searchResults', model:[searchresults:list])
    }
    
    def userDataAsJSON = {
        println "JSON"
        def list = []
        
        //take searchresult form _searchresult and tokenize into String Array
        def result = params.searchresults
        result = result.substring(1, result.length()-1)
        println (result)
        def allUserString = result.tokenize(', ')
        
        //search for items that match searchresult array and sort it according to params
        def allUsers = User.findAllByNameInList(allUserString, params)

        response.setHeader("Cache-Control", "no-store")
        allUsers.each {
            //add to JSON result
            list << [
                id:it.id,                
                name: '<a href="/voucher/gifting/'+it.id+'">' + it.name + '</a>',       
                username:it.username,
                lastname:it.lastname,
                address1:it.address1,
                postal:it.postal        
            ]
        }
        
        def data = [
            totalRecords: allUserString.size(),
            results: list
        ]
        render data as JSON
    }
    
    
    def giftingAll={} 
       
    def AddValueAll={
        (2..User.count()).each{
            def newVoucher = new Voucher (amount:params.value)
            newVoucher.save()
            def user=User.get(it)
            if (user){
                user.addToVoucher(newVoucher)
                if(user.save()){
                    flash.message="Successfully assigned voucher"
                    
                    mailService.sendMail {
                        to user.username
                        from "p.sireetorn@gmail.com"
                        subject "Congratulations. You've gotten a voucher from Toonwatch.com"
                        body """
                                    Hi,

                                    You are rewarded a voucher worth ${params.value}.
                                    ${params.message}

                                    Best Regards,
                                    ToonWatch.
                                    """
                    } 
                }else{
                                
                    flash.message="Invalid User Id"
                }
            }
            redirect(action:"list")    
        }  
    }
   
    def gifting={
        println(params.id)
        def user = User.findById(params.id)
        assert user
        return [user : user]
        
    }
   
    def addValue={ 
        println "specific user" 
        def newVoucher = new Voucher(amount:params.value)
        newVoucher.save()
        println(params.id)
        def user=User.get(params.id)
        if (user){
            user.addToVoucher(newVoucher)
            if(user.save()){
                flash.message="Successfully assigned voucher"
                //def body="A voucher worth SGD"+params.value+" is given to you"
                mailService.sendMail {
                    to user.username
                    from "p.sireetorn@gmail.com"
                    subject "Congratulations. You've gotten a voucher from Toonwatch.com"
                    body """
                                    Hi,

                                    You are rewarded a voucher worth ${params.value}.
                                    ${params.message}

                                    Best Regards,
                                    ToonWatch.
                                    """

                }
            }else{
                flash.message="Invalid User Id"
            }
        }  
        redirect(action:"list")           
    }
                                                       
    def newsletter={}
    def newsletterUI={
        def user = springSecurityService.currentUser
        if (user.newsletter==true){
            redirect(action:"alrSubscribed") 
        }
        else{
            redirect(url:"http://toonwatch.comp.nus.edu.sg/voucher/newsletterUI.gsp") 
        }
    }
  
    def sendnewsletter={
        println "sendnewsletter"
        def userList = User.findAll()
        userList.each{user->
            if(user.newsletter){
                mailService.sendMail {
                    to user.username
                    from "p.sireetorn@gmail.com"
                    subject "${params.subject}"
                    html 'Dear '+"${user.name}"+',<br/><br/>'+"${params.body}"+'<br/><br/>Best Regards,<br/>ToonWatch'
                
                                   
                }    
            }
        }
        flash.message =  "You have successfully sent out newsletter."
        redirect(action:"newsletter") 
    }
  
    def subscribeNews={
        def user = springSecurityService.currentUser
        if (user.newsletter==true){
            redirect(action:"alrSubscribed") 
        }
        else{
            user.newsletter= true
            redirect(action:"alrSubscribed") 
        }
    }
    
    def alrSubscribed={}
    
    def unSubscribeNews={
        def user = springSecurityService.currentUser
        if (user.newsletter!=true){
            redirect(action:"newsletterUI") 
        }
        else{
            user.newsletter= false
            flash.message="You have unsubscribed from our newsletter."
            redirect(action:"newsletterUI") 
        }
    }
         
            
    def list = {
        params.max = Math.min(params.max ? params.int('max') : 10, 100)
        [voucherInstanceList: Voucher.list(params), voucherInstanceTotal: Voucher.count()]
    }

    def create = {
        def voucherInstance = new Voucher()
        voucherInstance.properties = params
        return [voucherInstance: voucherInstance]
    }

    def save = {
        def voucherInstance = new Voucher(params)
        if (voucherInstance.save(flush: true)) {
            flash.message = "${message(code: 'default.created.message', args: [message(code: 'voucher.label', default: 'Voucher'), voucherInstance.id])}"
            redirect(action: "show", id: voucherInstance.id)
        }
        else {
            render(view: "create", model: [voucherInstance: voucherInstance])
        }
    }

    def show = {
        def voucherInstance = Voucher.get(params.id)
        if (!voucherInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'voucher.label', default: 'Voucher'), params.id])}"
            redirect(action: "list")
        }
        else {
            [voucherInstance: voucherInstance]
        }
    }

    def edit = {
        def voucherInstance = Voucher.get(params.id)
        if (!voucherInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'voucher.label', default: 'Voucher'), params.id])}"
            redirect(action: "list")
        }
        else {
            return [voucherInstance: voucherInstance]
        }
    }

    def update = {
        def voucherInstance = Voucher.get(params.id)
        if (voucherInstance) {
            if (params.version) {
                def version = params.version.toLong()
                if (voucherInstance.version > version) {
                    
                    voucherInstance.errors.rejectValue("version", "default.optimistic.locking.failure", [message(code: 'voucher.label', default: 'Voucher')] as Object[], "Another user has updated this Voucher while you were editing")
                    render(view: "edit", model: [voucherInstance: voucherInstance])
                    return
                }
            }
            voucherInstance.properties = params
            if (!voucherInstance.hasErrors() && voucherInstance.save(flush: true)) {
                flash.message = "${message(code: 'default.updated.message', args: [message(code: 'voucher.label', default: 'Voucher'), voucherInstance.id])}"
                redirect(action: "show", id: voucherInstance.id)
            }
            else {
                render(view: "edit", model: [voucherInstance: voucherInstance])
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'voucher.label', default: 'Voucher'), params.id])}"
            redirect(action: "list")
        }
    }

    def delete = {
        def voucherInstance = Voucher.get(params.id)
        if (voucherInstance) {
            try {
                voucherInstance.delete(flush: true)
                flash.message = "${message(code: 'default.deleted.message', args: [message(code: 'voucher.label', default: 'Voucher'), params.id])}"
                redirect(action: "list")
            }
            catch (org.springframework.dao.DataIntegrityViolationException e) {
                flash.message = "${message(code: 'default.not.deleted.message', args: [message(code: 'voucher.label', default: 'Voucher'), params.id])}"
                redirect(action: "show", id: params.id)
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'voucher.label', default: 'Voucher'), params.id])}"
            redirect(action: "list")
        }
    }
}
